<?php
	class CmsEmailTemplate extends CmsAppModel
	{
		var $name = 'EmailTemplate';
		var $validate = array('body_text'=>VALID_NOT_EMPTY,'body_html'=>VALID_NOT_EMPTY,'subject'=>VALID_NOT_EMPTY,'name'=>VALID_NOT_EMPTY);
		function addSameTemplate($content='',$data= array())
		{
			$this->create();
			return $this->save(array('EmailTemplate'=>am($data,array('body_text'=>$content,'body_html'=>$content))));
		}
		
		/**
		 * Return whether present template is present or not
		 * @param $template
		 */
		function hasTemplate($template)
		{
			return $this->hasAny(array('name'=>$template));
		}
		
		/**
		 * Returns content of given template for 
		 * the given email type.
		 * @param $template
		 * @param $type
		 */
		function getContent($template,$type='html')
		{
			if($type=='html')
				$field = 'body_html';
			else
				$field = 'body_text';
			return $this->field($field,array('name'=>$template));
		}
		/**
		 * search for subject in db.
		 * @param $template
		 */
		function getSubject($template)
		{
			$subject = false;
			if($this->hasField('subject'))
			{
				$subject = $this->field('subject',array('name'=>$template));
			}
			return $subject;
		}
		
		function resetEmailTemlates($filePath = '',$templateNames = array(),$subjects = array())
		{		
      $i = 0;
      $data = array();
			foreach($templateNames as $tempName=>$config)
			{
				$fileName = 'template_'.$tempName.'.ctp';
        if($this->hasTemplate($tempName))
        {
            continue;
        }
				$filePathToRead = $filePath.DS.$fileName;
				$mailSubject = '';
				if(isset($subjects['subject_'.$tempName]) && !empty($subjects['subject_'.$tempName]))
				{
					$mailSubject = $subjects['subject_'.$tempName];
				}			
				$content = file_get_contents($filePathToRead);
				$data[$i]['EmailTemplate'] =  array('body_text'=>$content,'body_html'=>$content,'subject'=>$mailSubject,'name'=>$tempName);
				$i++;
				$filePathToRead = null;			
			}
      if($data)
			{
          $this->create();
        $this->saveAll($data,array('validate'=>false,'callbacks'=>false));
      }
			return true;
		}
	}	

?>